; CHR$(x, y, x) returns the string CHR$(x) + CHR$(y) + CHR$(z)
#include once <alloc.asm>
CHR:
; Returns HL = Pointer to STRING (NULL if no memory)
; Requires alloc.asm for dynamic memory heap.
; Parameters: HL = Number of bytes to insert (already push onto the stack)
; STACK => parameters (16 bit, only the High byte is considered)
; Used registers A, A', BC, DE, HL, H'L'
                     ;- PROC
                     ;- LOCAL __POPOUT
                     ;- LOCAL TMP
                     ;- TMP		EQU 23629 ; (DEST System variable)
lda z80_h            ;- ld a,h
sta z80_a
ora z80_l            ;- or l
bne *+3              ;- ret z	; If Number of parameters is ZERO, return NULL STRING
rts
lda z80_h            ;- ld b,h
sta z80_b
lda z80_l            ;- ld c,l
sta z80_c
pla                  ;- pop hl	; Return address
sta z80_h
pla
sta z80_l
lda z80_l            ;- ld (TMP),hl
sta TMP
lda z80_h
sta TMP+1
lda z80_c            ;- push bc
pha
lda z80_b
pha
inc z80_c            ;- inc bc
bne *+4
inc z80_b
inc z80_c            ;- inc bc	; BC = BC + 2 => (2 bytes for the length number)
bne *+4
inc z80_b
jsr __MEM_ALLOC      ;- call __MEM_ALLOC
pla                  ;- pop bc
sta z80_b
pla
sta z80_c
lda z80_h            ;- ld d,h
sta z80_d
lda z80_l            ;- ld e, l			; Saves HL in DE
sta z80_e
lda z80_h            ;- ld a,h
sta z80_a
ora z80_l            ;- or l
jeq __POPOUT         ;- jr z, __POPOUT	; No Memory, return
lda z80_c            ;- ld (hl),c
ldy #$00
sta (z80_hl),y
inc z80_l            ;- inc hl
bne *+4
inc z80_h
lda z80_b            ;- ld (hl),b
ldy #$00
sta (z80_hl),y
inc z80_l            ;- inc hl
bne *+4
inc z80_h

__POPOUT:	; Removes out of the stack every byte and return
; If Zero Flag is set, don't store bytes in memory
ldx z80_ap           ;- ex af, af' ; Save Zero Flag
sta z80_ap
txa
lda z80_b            ;- ld a,b
sta z80_a
ora z80_c            ;- or c
jeq __CHR_END        ;- jr z, __CHR_END
                     ;- dec bc
plp                  ;- pop af 	   ; Next byte
pha
ldx z80_ap           ;- ex af, af' ; Recovers Zero flag
sta z80_ap
txa
jeq __POPOUT         ;- jr z,__POPOUT
ldx z80_ap           ;- ex af,af' ; Saves Zero flag
sta z80_ap
txa
lda z80_a            ;- ld (hl),a
ldy #$00
sta (z80_hl),y
inc z80_l            ;- inc hl
bne *+4
inc z80_h
ldx z80_ap           ;- ex af, af' ; Recovers Zero Flag
sta z80_ap
txa
jmp __POPOUT         ;- jp __POPOUT

__CHR_END:
lda TMP              ;- ld hl,(TMP)
sta z80_l
lda TMP+1
sta z80_h
lda z80_l            ;- push hl		; Restores return addr
pha
lda z80_h
pha
lda z80_e            ;- ex de,hl	; Recovers original HL ptr
ldx z80_l
stx z80_e
sta z80_l
lda z80_d
ldx z80_h
stx z80_d
sta z80_h
rts                  ;- ret
                     ;- ENDP

